import { Image, ImageBackground, StyleSheet, Text, TouchableOpacity, View } from 'react-native'
import React, { useCallback, useEffect, useState } from 'react'
import { getScreenHeight, getScreenWidth } from '@/utils/auto'
import { Feather } from '@expo/vector-icons'
import { ActionSheet, Button, List, Modal, Picker, Provider } from '@ant-design/react-native'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { router, useFocusEffect } from 'expo-router'
import * as ImagePicker from 'expo-image-picker'

const Item = List.Item

const UserInfo = () => {

    const [gender, setGender] = useState('')
    const [isPickerVisible, setPickerVisible] = useState(false) // 控制性别选择器的显示
    const [avatar, setAvatar] = useState('')

    const EditPhone = () => {
        Modal.prompt(
            'Phone',
            'Edit Phone',
            (val) => {
                AsyncStorage.setItem('userInfo', JSON.stringify({ ...info, phone: val }))
                fetchUserInfo()
            },
            'default',
            '',
            ['please input phone'],
        )
    }

    const EditName = () => {
        Modal.prompt(
            'Name',
            'Edit Name',
            (val) => {
                AsyncStorage.setItem('userInfo', JSON.stringify({ ...info, user: val }))
                fetchUserInfo()
            },
            'default',
            '',
            ['please input name'],
        )
    }

    const genderOptions = [
        {
            label: '男',
            value: '男',
        },
        {
            label: '女',
            value: '女',
        },
    ]

    const onGenderChange = (value: any) => {
        //修改本地存储的数据
        AsyncStorage.setItem('userInfo', JSON.stringify({ ...info, sex: value }))
        fetchUserInfo()
        setPickerVisible(false) // 选择完毕后关闭选择器
    }
    const [info, setInfo] = useState({
        user: '请登录',
        phone: '',
        image: 'https://img0.baidu.com/it/u=1240274933,2284862568&fm=253&fmt=auto&app=138&f=PNG?w=180&h=180',
        sex: ''
    })

    const fetchUserInfo = async () => {
        try {
            const res = await AsyncStorage.getItem('userInfo');
            if (res) {
                setInfo(JSON.parse(res));
            }
        } catch (error) {
            console.error('Error fetching user info:', error);
        }
    };

    useFocusEffect(
        useCallback(() => {
            fetchUserInfo();
        }, []) // 依赖数组为空，确保只在组件挂载时运行一次
    );

    const showActionSheet = () => {
        const BUTTONS = [
            '相册',
            '拍照',
            '取消',
        ]
        ActionSheet.showActionSheetWithOptions(
            {
                title: '修改头像',
                options: BUTTONS,
                cancelButtonIndex: 2, // 取消按钮的索引
            },
            async (buttonIndex: any) => {
                if (buttonIndex === 0) {
                    // 从相册中选择
                    router.push('/picker')
                } else if (buttonIndex === 1) {
                    // 拍照
                    router.push('/camera')
                }
            },
        )
    }

    return (
        <Provider>
            <View style={styles.container}>
                <View style={styles.avatarBox}>
                    <TouchableOpacity onPress={() => { showActionSheet() }}>
                        <ImageBackground
                            style={styles.avatar} resizeMode='contain'
                            source={{ uri: info.image || avatar }}
                        >
                            <Feather name="camera" size={30} color="white" />
                        </ImageBackground>
                    </TouchableOpacity>
                </View>

                <View style={styles.body}>
                    <List>
                        <Item
                            extra={info.phone}
                            onPress={EditPhone}
                        >
                            手机号
                        </Item>
                        <Item
                            extra={info.user}
                            onPress={EditName}
                        >
                            昵称
                        </Item>
                        <Item
                            extra={info.sex}
                            onPress={() => {
                                setPickerVisible(true) // 点击后显示选择器
                            }}
                        >
                            性别
                        </Item>
                    </List>
                </View>

                {/* 性别选择器，控制其可见性 */}
                {isPickerVisible && (
                    <List renderHeader={'选择性别'}>
                        <Picker
                            data={genderOptions}
                            cols={1}
                            value={[gender]}
                            onChange={(v) => onGenderChange(v[0])}
                            onOk={(v) => onGenderChange(v[0])}
                            onDismiss={() => setPickerVisible(false)} // 点击空白处关闭选择器
                            visible={isPickerVisible}
                        >
                            <List.Item arrow="horizontal">性别选择</List.Item>
                        </Picker>
                    </List>
                )}

            </View >
        </Provider>
    )
}

export default UserInfo

const styles = StyleSheet.create({
    container: {
        width: getScreenWidth(),
        height: getScreenHeight(),
        backgroundColor: "rgb(245,248,255)"
    },
    avatarBox: {
        width: getScreenWidth(),
        height: getScreenHeight() / 5,
        backgroundColor: "rgb(245,248,255)",
        alignItems: "center",
        justifyContent: "center"
    },
    avatar: {
        width: 80,
        height: 80,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "#f0f0f0"
    },
    body: {
        width: getScreenWidth(),
        padding: 20
    }
})